import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Col, Form, Input, Row, Select, Spin, message } from 'antd';
import { Ref, useEffect, useMemo, useRef, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { getColorTextLoadMap, getLoadMapList, getPosIDs, getTenantID, getUserID, getUserName, onCloseModalCommon } from '@/utils';
import { batchCompleteService, cancelTaskService, completeService, resolveTaskService, getTagService, addTagService, delTagService } from '../services';

import { ILoadMapTypeAll } from '@/common';
import { TagSelectNew } from '@/components/TagsSelectNew';

interface IWorkFlowHandModalAPI {
  onClose: () => void;
  flowDetailInfo: Record<string, any>;
  requestController: string;
  reloadCallback: () => void;
  checkItemObj: Record<string, any>;
  handHelpType?: boolean;
  checkflowList: Record<string, any>[];
  detailInfoObj?: Record<string, any>;
  isCounterObj?: Record<string, any>;
}

export const WorkFlowHandModal: React.FC<IWorkFlowHandModalAPI> = ({
  onClose,
  flowDetailInfo,
  requestController,
  reloadCallback,
  checkItemObj,
  handHelpType = false,
  checkflowList = [],
  detailInfoObj = {},
  isCounterObj = {},
}) => {
  /**弹框的ref*/
  const workFlowHandModalRef: Ref<IOneModalRef> = useRef(null);

  /** 流程办理 */
  const [workflowForm] = Form.useForm();

  /** 获取数据字典loadMdicMap */
  const { loadMapInfo, mapLoading } = getLoadMapList([`${getTenantID()}${ILoadMapTypeAll.OFTENCHECK_COMMENT}`]);

  /** 保存当前选中节点数据 */
  const [checkNodeInfo, setCheckNodeInfo] = useState<Record<string, any>>({});

  /** loading */
  const [fLoading, setfloading] = useState<boolean>(false);

  /** 初始化 */
  useEffect(() => {
    if (checkItemObj && checkItemObj?.flowValue) {
      if (checkItemObj?.flowValue === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1005`) {
        workflowForm?.setFieldsValue({
          intention: checkItemObj?.flowValue,
          comment: `流程已被${getUserName()}撤回！`,
        });
      } else {
        workflowForm?.setFieldsValue({
          intention: checkItemObj?.flowValue,
          comment: checkItemObj?.flowText,
        });
      }

      setCheckNodeInfo(checkItemObj);
    }
  }, [checkItemObj]);

  /** 作废回调 */
  const cancelCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      onCloseModalCommon(workFlowHandModalRef);
      reloadCallback();
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入作废接口 */
  const { cancelTaskLoading, cancelTaskRun } = cancelTaskService(cancelCallback, requestController);

  /**
   * 办理流程回调
   * @param res
   */
  const completeCallBack = (res: any) => {
    if (res && res?.msgFlag) {
      /** 判断是否调用作废按钮 */
      if (
        detailInfoObj &&
        detailInfoObj?.state == `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1003` &&
        detailInfoObj?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1000` &&
        checkNodeInfo?.flowValue == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1000`
      ) {
        cancelTaskRun({
          id: detailInfoObj?.id,
          versionNum: detailInfoObj?.versionNum,
        });
      } else {
        onCloseModalCommon(workFlowHandModalRef);
        message.success(res?.msg);
        reloadCallback();
      }
    } else {
      message.error(res?.msg);
    }
  };

  /**个人标签回调 */
  const tagListCallBack = (res) => {
    let option: Record<string, any>[] = [];
    if (res.msgFlag && res.obj) {
      res.obj?.forEach((item: any) => {
        option?.push({
          value: item?.id,
          name: item?.tagName,
        });
      });
    }
    setTagList(option);
  };
  /**添加标签回调 */
  const addTagListCallBack = (res) => {
    if (res.msgFlag && res.obj) {
      setTagList([...tagList, { value: res.obj.id, name: res.obj.tagName }]);
    }
  };
  /**删除标签回调 */
  const delTagListCallBack = (res) => {
    if (res.msgFlag) {
      tagTaskRun();
    }
  };

  /**个人标签列表 */
  const [tagList, setTagList] = useState<Record<string, any>[]>([]);

  /** 引入办理流程接口 */
  const { completeLoading, completeRun } = completeService(completeCallBack, requestController);

  /** 引入批量办理撤回接口 */
  const { batchCompleteLoading, batchCompleteRun } = batchCompleteService(requestController);

  /** 引入帮办流程接口 */
  const { resolveTaskLoading, resolveTaskRun } = resolveTaskService(completeCallBack, requestController);

  /** 引入获取审核常用标签接口 */
  const { tagTaskRun } = getTagService(tagListCallBack);

  /** 引入添加审核常用标签接口 */
  const { addTagTaskRun } = addTagService(addTagListCallBack);

  /** 引入删除审核常用标签接口 */
  const { delTagTaskRun } = delTagService(delTagListCallBack);

  useEffect(() => {
    tagTaskRun();
  }, []);

  const addTag = (tagName) => {
    addTagTaskRun({
      tagName,
    });
  };

  const delTag = (id) => {
    delTagTaskRun({
      id,
    });
  };

  /** 保存 */
  const onSaveHand = () => {
    workflowForm?.validateFields()?.then(async (values: any) => {
      const intentionItem: Record<string, any> | any = checkflowList?.find((item: any) => item?.flowValue == values?.intention);
      setCheckNodeInfo(intentionItem);
      /** 批量撤回的办理 */
      if (
        isCounterObj?.taskIsSign &&
        isCounterObj?.taskIsSign == 1 &&
        intentionItem?.flowValue == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1005` // 被撤回
      ) {
        setfloading(true);
        await handleBatchCompleteRun(isCounterObj.taskList, values, intentionItem, 0, isCounterObj?.isCurrent);
      } else {
        /** 普通情况的办理 */
        const params: any = {
          ...values,
          ...intentionItem,
          id: flowDetailInfo?.id,
          orderID: flowDetailInfo?.orderID,
          taskIsSign: flowDetailInfo?.taskIsSign,
          procInstID: flowDetailInfo?.procInstID,
          procDefID: flowDetailInfo?.procDefID,
          assigneeID: getUserID(),
          assigneePositionID: getPosIDs(),
        };

        delete params['oftenComment'];
        if (handHelpType) {
          resolveTaskRun(params);
        } else {
          /** 判断办理是否是撤回，如果是撤回的话就需要变更人的信息 */
          if (intentionItem?.flowValue && intentionItem?.flowValue == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1005`) {
            params.assigneeID = flowDetailInfo?.assigneeID;
            params.assigneePositionID = flowDetailInfo?.assigneePositionID;
          }
          completeRun(params);
        }
      }
    });
  };

  /** 递归调用-延时1秒-办理接口 */
  const handleBatchCompleteRun = async (taskList: any[], values: any, intentionItem: any, index: number, isCurrent) => {
    if (index < taskList.length) {
      let params = {
        ...values,
        ...intentionItem,
      };

      if (isCurrent) {
        /**
         * 当前节点是普通节点，上一个节点是会签节点
         * 批量撤回，由上一个会签节点中的人来撤回
         * 入参使用当前人的
         * */
        params.id = flowDetailInfo?.id;
        params.orderID = flowDetailInfo?.orderID;
        params.taskIsSign = flowDetailInfo?.taskIsSign;
        params.procInstID = flowDetailInfo?.procInstID;
        params.procDefID = flowDetailInfo?.procDefID;
        params.assigneeID = flowDetailInfo?.assigneeID;
        params.assigneePositionID = flowDetailInfo?.assigneePositionID;
      } else {
        /**
         * 当前节点是会签节点，上一个节点是普通节点
         * 如果当前会签中的人都办理完成了，那么不会进入这里，会进入上方的判断
         * 进入这里说明 当前会签任务没有全部都未审核，进行批量撤回，
         * 入参使用任务集合中的相对应的人
         * 注意: 会签如果有人办理 且 还有人没办理的情况下，依然不可撤回
         * */
        params.id = taskList[index]?.id;
        params.orderID = taskList[index]?.orderID;
        params.taskIsSign = taskList[index]?.taskIsSign;
        params.procInstID = taskList[index]?.procInstID;
        params.procDefID = taskList[index]?.procDefID;
        params.assigneeID = taskList[index]?.assigneeID;
        params.assigneePositionID = taskList[index]?.assigneePositionID;
      }

      delete params['oftenComment'];
      await batchCompleteRun(params);
      setTimeout(async () => {
        await handleBatchCompleteRun(taskList, values, intentionItem, index + 1, isCurrent);
      }, 1000);
    } else {
      setfloading(false);
      onCloseModalCommon(workFlowHandModalRef);
      reloadCallback();
    }
  };

  /** 处理常用审批意见 */
  const oftenCommentMemo = useMemo(() => {
    let option: Record<string, any>[] = [];
    loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.OFTENCHECK_COMMENT}`]?.forEach((item: any) => {
      option?.push({
        value: item?.id,
        name: item?.name,
      });
    });
    return option;
  }, [loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.OFTENCHECK_COMMENT}`]]);

  return (
    <OneModal
      open={true}
      title={handHelpType ? '流程帮办' : '流程办理'}
      centered={true}
      ref={workFlowHandModalRef}
      width={document.body.clientWidth * 0.3}
      confirmLoading={completeLoading || resolveTaskLoading || mapLoading || cancelTaskLoading || batchCompleteLoading || fLoading} // loading
      onOk={onSaveHand}
      onCancel={onClose}
      bodyStyle={{ padding: '5px 10px' }}
    >
      <Spin spinning={completeLoading || resolveTaskLoading || mapLoading || cancelTaskLoading || batchCompleteLoading || fLoading}>
        <div className={pageStyles['fromView-styles']}>
          <Form form={workflowForm}>
            <Row>
              <Col span={24}>
                <Form.Item
                  name="intention"
                  label="审批意向"
                  rules={[
                    {
                      required: true,
                      message: '请选择审批意向',
                    },
                  ]}
                  initialValue={checkflowList?.[0]?.flowValue}
                >
                  <Select placeholder="请选择审核意向" disabled={true}>
                    {checkflowList?.map((item: any) => {
                      const { colorText } = getColorTextLoadMap(item?.flowName);
                      return (
                        <Select.Option key={item?.flowValue} value={item?.flowValue}>
                          {colorText}
                        </Select.Option>
                      );
                    })}
                  </Select>
                </Form.Item>
              </Col>

              <Col span={24}>
                <Form.Item
                  label={'审核意见'}
                  name="comment"
                  rules={[
                    {
                      required: true,
                      message: '请输入审核意见',
                    },
                  ]}
                >
                  <Input.TextArea placeholder={`请输入审核意见`} showCount maxLength={500} autoSize={{ minRows: 3, maxRows: 5 }} />
                </Form.Item>
              </Col>

              {checkItemObj?.flowValue === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_HANDRESULT}1005` ? (
                <></>
              ) : (
                <TagSelectNew
                  colSpan={24}
                  formLabel="常用审核意见"
                  formName="oftenComment"
                  radioList={tagList}
                  onChange={(infoName: any) => {
                    // const infoName: string = oftenCommentMemo?.find((item: any) => item?.value == infoKey)?.name;
                    workflowForm?.setFieldsValue({
                      comment: infoName,
                    });
                  }}
                  onAddTag={(tagName) => {
                    addTag(tagName);
                  }}
                  onDelTag={(id) => {
                    delTag(id);
                  }}
                />
              )}

              {/* <Select
                    placeholder="请选择常用审核意见"
                    loading={mapLoading}
                    onSelect={(_selectKey: string, otherInfo: any) => {
                      workflowForm?.setFieldsValue({
                        comment: otherInfo?.children,
                      });
                    }}
                  >
                    {loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.OFTENCHECK_COMMENT}`]?.map((item: any) => {
                      return (
                        <Select.Option key={item?.id} value={item?.id}>
                          {item?.name}
                        </Select.Option>
                      );
                    })}
                  </Select> */}

              {/* <UploadFormCommon
                form={workflowForm}
                fileFormName={'attachUrl'}
                spanCol={24}
                inRowProportion={24}
                name={'attachFile'}
                label="附件"
                required={false}
                accept={'.jpg|.png|.jpeg|.doc|.docx'}
                url={`/${requestController}/uploadFile`}
                downloadUrl={`/${requestController}/downloadFile`}
                fileFormDelName={'delLicenceUrl'}
                delFunc={() => { }}
                maxFile={1}
                defaultFiles={null}
              >
                上传附件
              </UploadFormCommon>

              <Col span={24}>
                <Form.Item label={'附件描述'} name="attachDescribe">
                  <Input.TextArea
                    placeholder={`请输入附件描述`}
                    showCount
                    maxLength={200}
                    autoSize={{ minRows: 2, maxRows: 4 }}
                  />
                </Form.Item>
              </Col> */}
            </Row>
          </Form>
        </div>
      </Spin>
    </OneModal>
  );
};
